package com.express.gateway.spi.check.impl;

import com.express.gateway.common.CommonCons;
import com.express.gateway.common.ResultFormat;
import com.express.gateway.manage.entity.Api;
import com.express.gateway.manage.enums.StatusCodeEnum;
import com.express.gateway.spi.check.FileCheckHandler;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.express.gateway.manage.enums.ContentTypeEnum.MULTIPART_FORM_DATA;

public class FileCheckHandlerImpl implements FileCheckHandler {
    private static final Logger LOG = LogManager.getLogger(FileCheckHandlerImpl.class);

    Api api;
    public FileCheckHandlerImpl(Api api) {
        this.api = api;
    }

    @Override
    public void handle(RoutingContext rct) {
        boolean success = false;
        String contentType = rct.request().headers().get(CommonCons.CONTENT_TYPE);
        if (MULTIPART_FORM_DATA.val().equalsIgnoreCase(contentType)) {
            success = checkFormDataFileContent(rct);
        }
        // 检查完成无问题继续下一步
        if (success) {
            rct.next();
            return;
        }
         // 检测不通过则直接返回信息
        rct.response().end(StatusCodeEnum.C1407.into());
    }

    private boolean checkFormDataFileContent(RoutingContext rct) {
        Map<String, Long> uploadMap = api.getUploadParam();
        List<FileUpload> fileUploadList = rct.fileUploads();
        for (FileUpload fileUpload : fileUploadList) {
            String fileType = fileUpload.contentType();
            Long size = uploadMap.get(fileType);
            long fileSize = fileUpload.size();
            LOG.info("name:{}, file name:{}, type:{}, size:{}", fileUpload.fileName(), fileUpload.uploadedFileName(), fileType, size);
            if (Objects.isNull(size) || fileSize > size) {
                return false;
            }
        }
        // 写文件上传标记
        rct.request().headers().add("FILE_UPLOAD", "1");;
        return true;
    }
}
